<template>
  <el-button type="primary" @click="add" v-hasAuth="'user:add'">新增用户</el-button>
  <el-button type="danger" @click="batchDel" v-hasAuth="'user:delete'">批量删除</el-button>

  <el-table
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange">

    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="55" />
    <el-table-column label="账号">
      <template #default="scope"><!--插槽-->
        {{ scope.row.loginAct }}
      </template>
    </el-table-column>
    <el-table-column property="name" label="姓名" width="120" />
    <el-table-column property="phone" label="手机" show-overflow-tooltip />
    <el-table-column property="email" label="邮箱" show-overflow-tooltip />
    <el-table-column property="createTime" label="创建时间" show-overflow-tooltip />
    <el-table-column label="操作" show-overflow-tooltip>
      <template #default="scope"><!--插槽-->
        <el-button type="primary" @click="view(scope.row.id)" v-hasAuth="'user:view'">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)" v-hasAuth="'user:edit'">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)" v-hasAuth="'user:delete'">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @current-change="page"
      @prev-click="page"
      @next-click="page" />

  <!--查看用户详情的弹窗（对话框）-->
  <el-dialog v-model="userDetailDialogVisible" title="用户详情" width="55%" :center="true" :draggable="true">
    <el-form :model="userDetail" label-width="110px">

      <el-form-item label="ID：">
        <div class="userItem">&nbsp;{{userDetail.id}}</div>
      </el-form-item>

      <el-form-item label="账号：">
        <div class="userItem">&nbsp;{{userDetail.loginAct}}</div>
      </el-form-item>

      <el-form-item label="密码：">
        <div class="userItem">&nbsp;******</div>
      </el-form-item>

      <el-form-item label="姓名：">
        <div class="userItem">&nbsp;{{userDetail.name}}</div>
      </el-form-item>

      <el-form-item label="手机：">
        <div class="userItem">&nbsp;{{userDetail.phone}}</div>
      </el-form-item>

      <el-form-item label="邮箱：">
        <div class="userItem">&nbsp;{{userDetail.email}}</div>
      </el-form-item>

      <el-form-item label="账号未过期：">
        <div class="userItem">&nbsp;{{userDetail.accountNoExpired === 1 ? '是' : '否'}}</div>
      </el-form-item>

      <el-form-item label="密码未过期：">
        <div class="userItem">&nbsp;{{userDetail.credentialsNoExpired === 1 ? '是' : '否'}}</div>
      </el-form-item>

      <el-form-item label="账号未锁定：">
        <div class="userItem">&nbsp;{{userDetail.accountNoLocked === 1 ? '是' : '否'}}</div>
      </el-form-item>
      <el-form-item label="账号未失效：">
        <div class="userItem">&nbsp;{{userDetail.accountEnabled === 1 ? '是' : '否'}}</div>
      </el-form-item>
      <el-form-item label="创建时间：">
        <div class="userItem">&nbsp;{{userDetail.createTime}}</div>
      </el-form-item>
      <el-form-item label="创建人：">
        <div class="userItem">&nbsp;{{userDetail.createByDO.name}}</div>
      </el-form-item>
      <el-form-item label="编辑时间：">
        <div class="userItem">&nbsp;{{userDetail.editTime}}</div>
      </el-form-item>
      <el-form-item label="编辑人：">
        <div class="userItem">&nbsp;{{userDetail.editByDO.name}} </div>
      </el-form-item>
      <el-form-item label="最近登录时间：">
        <div class="userItem">&nbsp;{{userDetail.lastLoginTime}}</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userDetailDialogVisible = false">关 闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!--添加、编辑用户的弹窗（对话框）-->
  <el-dialog v-model="addUserDialogVisible" :title="userQuery.id > 0 ? '编辑用户' : '添加用户'" width="55%" :center="true" :draggable="true">
    <el-form ref="userRefForm" :model="userQuery" label-width="110px" :rules="userFormRules">

      <el-form-item label="账号：" prop="loginAct">
        <el-input v-model="userQuery.loginAct" />
      </el-form-item>

      <el-form-item label="密码：" :prop="userQuery.id > 0 ? '' : 'loginPwd'">
        <el-input type="password" v-model="userQuery.loginPwd" />
      </el-form-item>

      <el-form-item label="姓名：" prop="name">
        <el-input v-model="userQuery.name" />
      </el-form-item>

      <el-form-item label="手机：" prop="phone">
        <el-input v-model="userQuery.phone" />
      </el-form-item>

      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="userQuery.email" />
      </el-form-item>

      <el-form-item label="账号未过期：" prop="accountNoExpired">
        <el-select v-model="userQuery.accountNoExpired" clearable placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="密码未过期：" prop="credentialsNoExpired">
        <el-select v-model="userQuery.credentialsNoExpired" clearable placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="账号未锁定：" prop="accountNoLocked">
        <el-select v-model="userQuery.accountNoLocked" clearable placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="账号未失效：" prop="accountEnabled">
        <el-select v-model="userQuery.accountEnabled" clearable placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="userSubmit">提 交</el-button>
        <el-button @click="addUserDialogVisible = false">关 闭</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script>
import {doDelete, doGet, doPost, doPut} from "@/http/httpRequest";
import {messageConfirm, messageTip} from "@/util/util";

export default {

  //注入父页面提供的数据
  inject : ['reload', 'user', 'description', 'age', 'idArray'],

  data() {
    return {
      //定义用户列表对象
      userList : [{}],
      //分页时每页显示多少条数据，初始值是0
      pageSize : 0,
      //分页时总共有多少条数据，初始值是0
      total : 0,
      //用户详情的弹窗控制变量，true就弹出来，false就不弹
      userDetailDialogVisible : false,
      //定义用户详情对象，初始值是空
      userDetail : {
        createByDO : {},
        editByDO : {}
      },
      //新增用户要提交的用户数据对象，初始值是空
      userQuery : {},
      //用户状态的下拉选项数据
      options : [
        {label : '是', value : 1},
        {label : '否', value : 0},
      ],
      //新增用户的弹窗控制变量，true就弹出来，false就不弹
      addUserDialogVisible : false,
      //定义新增用户的form表单验证规则
      userFormRules : {
        //验证登录账号字段（规则可以有多个，所以是一个数组）
        loginAct : [
          { required: true, message: '请输入登录账号', trigger: 'blur' }
        ],
        //验证登录密码字段（规则可以有多个，所以是一个数组）
        loginPwd : [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' },
        ],
        name : [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, message: '密码长度至少2个汉字', trigger: 'blur' },
          { pattern : /^[\u4e00-\u9fa5]{0,}$/, message: '姓名必须是中文汉字', trigger: 'blur'} //正则从网上找，然后测试一下对不对，chatgpt
        ],
        phone : [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern : /^1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur'}
        ],
        email : [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
        ],
        accountNoExpired : [
          { required: true, message: '请选择账号是否未过期', trigger: ['blur'] },
        ],
        credentialsNoExpired : [
          { required: true, message: '请选择密码是否未过期', trigger: ['blur'] },
        ],
        accountNoLocked : [
          { required: true, message: '请选择账号是否未未锁定', trigger: ['blur'] },
        ],
        accountEnabled : [
          { required: true, message: '请选择账号是否可用', trigger: ['blur'] },
        ]
      },
      //定义用户id的数组，初始值是空
      userIdArray : []
    }
  },

  mounted() {
    this.getData(1);
  },

  methods : {
    //current表示当前是查第几页
    getData(current) {
      doGet("/api/user", {
        current : current //前面的current是参数名，后面的current是参数值
      }).then(resp => {
        if (resp.data.code === 200) {
          this.userList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      })
    },

    //分页函数
    page(value) { //value就是要查询的那一页的页码
      this.getData(value);
    },

    //查看详情
    view(id) {
      //把窗弹出来
      this.userDetailDialogVisible = true;
      doGet("/api/user/" + id, {}).then(resp => {
        if (resp.data.code === 200) {
          this.userDetail = resp.data.data;
        }
      })
    },

    //新增用户
    add() {
      this.addUserDialogVisible = true;
      //新增用户，需要把userQuery对象置为空的
      this.userQuery = {};
    },

    //添加、编辑用户提交保存
    userSubmit() {
      this.$refs.userRefForm.validate( (isValid) => {
        if (isValid) { //true表示表单验证通过
          //可以提交表单
          let formData = new FormData(); //FormData是js对象
          for (let field in this.userQuery) {
            //循环userQuery对象，把该对象中的所有字段和值都追加到formData
            formData.append(field, this.userQuery[field]);
          }

          //编辑
          if (this.userQuery.id > 0) {
            doPut("/api/user", formData).then( resp => {
              if (resp.data.code === 200) {
                //编辑用户成功
                messageTip("编辑成功", "success");
                //刷新页面
                this.reload();
              } else {
                //编辑用户失败
                messageTip("编辑失败，原因：" + resp.data.msg, "error");
              }
            })
          } else {
            doPost("/api/user", formData).then( resp => {
              if (resp.data.code === 200) {
                //添加用户成功
                messageTip("添加成功", "success");
                //刷新页面
                this.reload();
              } else {
                //添加用户失败
                messageTip("添加失败，原因：" + resp.data.msg, "error");
              }
            })
          }
        }
      })
    },

    //编辑用户
    edit(id) {
      console.log(id);
      this.addUserDialogVisible = true;
      //查询该id的用户详情
      this.loadUserDetail(id);
    },

    //根据id加载用户详情
    loadUserDetail(id) {
      doGet("/api/user/" + id, {}).then(resp => {
        if (resp.data.code === 200) {
          this.userQuery = resp.data.data;
          this.userQuery.loginPwd = "";
        }
      })
    },

    //根据id删除用户
    del(id) {
      //提示用户，您确定要删除该数据吗？
      messageConfirm("您确定要删除该数据吗？").then(() => { //点“确定”就执行then()函数
        doDelete("/api/user/" + id, {}).then(ttt => {
          //then里面取结果，这个结果对象可以使用任何名字，不一定要使用过resp，我们此处使用的就是ttt
          if (ttt.data.code === 200) {
            messageTip("删除成功", "success");
            //刷新一下，局部刷新
            this.reload();
          } else {
            messageTip("删除失败，原因：" + ttt.data.msg, "error");
          }
        })
      }).catch(() => { //点“取消”就执行catch()函数
        messageTip("取消删除", "warning");
      })
    },

    //批量删除
    batchDel() {
      if (this.userIdArray.length <= 0) {
        //没有选择数据，提示一下用户
        messageTip("请选择要删除的数据", "warning");
        return;
      }
      //提示用户，您确定要删除这些数据吗？
      messageConfirm("您确定要删除这些数据吗？").then(() => { //点“确定”就执行then()函数
        // ids = "1,3,5,6,11,13,16";
        let ids = this.userIdArray.join(",");
        doDelete("/api/user", {
          ids : ids
        }).then(ttt => {
          //then里面取结果，这个结果对象可以使用任何名字，不一定要使用过resp，我们此处使用的就是ttt
          if (ttt.data.code === 200) {
            messageTip("批量删除成功", "success");
            //刷新一下，局部刷新
            this.reload();
          } else {
            messageTip("批量删除失败，原因：" + ttt.data.msg, "error");
          }
        })
      }).catch(() => { //点“取消”就执行catch()函数
        messageTip("取消批量删除", "warning");
      })
    },

    //用户在table表格中勾选或者取消勾选时，会触发执行该函数
    handleSelectionChange(rowItemArray) {
      this.userIdArray = [];
      rowItemArray.forEach( rowItem => {
        this.userIdArray.push(rowItem.id);
      })
    }
  }
}

</script>

<style scoped>
.el-table {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 15px;
}
.userItem {
  background: aliceblue;
  width: 100%;
}
.el-select {
  width: 100%;
}
</style>